package com.puchi.sdkdemo.app.came.activity;

import android.os.Bundle;
import com.zalyyh.mvvm.base.BaseActivity;

import com.puchi.sdkdemo.R;
import com.puchi.sdkdemo.BR;
import com.puchi.sdkdemo.databinding.ActivityGameBinding;
import com.puchi.sdkdemo.app.came.model.GameViewModel;

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.bumptech.glide.Glide
import com.bytedance.sdk.openadsdk.*
import com.orhanobut.logger.Logger
import com.zalyyh.advertisement.enty.AdaveData
import com.zalyyh.advertisement.interfac.AdverCallback
import com.zalyyh.advertisement.open.Adavert

import java.util.*
import android.widget.LinearLayout
import com.puchi.sdkdemo.utils.AllUtlis


class GameActivity : BaseActivity<ActivityGameBinding, GameViewModel>() {
    private var mTTAdNative: TTAdNative? = null
    var a = this
    private var mttRewardVideoAd: TTRewardVideoAd? = null
    private var mTTAd: TTNativeExpressAd? = null
    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_game;
    }

    override fun initVariableId(): Int {
        return BR.viewModel;
    }

    override fun initData() {
        super.initData();

        model.setData(this, binding);
        //step1:初始化sdk
        val ttAdManager = TTAdSdk.getAdManager()
        //step2:创建TTAdNative对象,用于调用广告请求接口
        mTTAdNative = ttAdManager.createAdNative(applicationContext)
        //step3:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        ttAdManager.requestPermissionIfNecessary(this)
        binding.btnRewardShow.setOnClickListener(View.OnClickListener {
            if (mttRewardVideoAd != null) {
                //step6:在获取到广告后展示
                //该方法直接展示广告
                //                    mttRewardVideoAd.showRewardVideoAd(RewardVideoActivity.this);

                //展示广告，并传入广告展示的场景
                mttRewardVideoAd!!.showRewardVideoAd(
                    a,
                    TTAdConstant.RitScenes.CUSTOMIZE_SCENES,
                    "scenes_test"
                )
                mttRewardVideoAd = null
            } else {
                setVideo()
                Toast.makeText(a, "请先加载广告", Toast.LENGTH_SHORT).show()
            }
        })
        binding.btnReward.setOnClickListener(View.OnClickListener {
            setVideo1()
        })
        binding.btnBanner.setOnClickListener(View.OnClickListener {
            var a = Adavert(a!!,object : AdverCallback(){
                override fun onError(var1: Int, var2: String) {
                    Logger.d(var2)
                }

                override fun show(data: AdaveData) {
                    val dialogView = LayoutInflater.from(a).inflate(R.layout.adv_view, null)
                    var view = dialogView.findViewById<View>(R.id.view)
                    val params = LinearLayout.LayoutParams( -1,AllUtlis.dp2px((data.wide/1.7).toFloat()))
                    view.layoutParams = params
                    binding.bannerContainer!!.removeAllViews()
                    binding.bannerContainer!!.addView(data.view)
                   // binding.bannerContainer!!.addView(dialogView)

                }
            })
            a.show(a.setAdSlot("939505337",500f,600f).build(),3)
        })
        setVideo()
    }


    private fun setVideo2() {
        val adSlot = AdSlot.Builder()
            .setCodeId("939505312")
            .setSupportDeepLink(true)
            .setImageAcceptedSize(600, 257)
            .setNativeAdType(AdSlot.TYPE_BANNER) //请求原生广告时候，请务必调用该方法，设置参数为TYPE_BANNER或TYPE_INTERACTION_AD
            .setAdCount(1)
            .build()
        //step5:请求广告，对请求回调的广告作渲染处理
        mTTAdNative!!.loadNativeAd(adSlot, object : TTAdNative.NativeAdListener {
            override fun onError(code: Int, message: String) {
                Toast.makeText(a, message, Toast.LENGTH_SHORT).show()

            }

            override fun onNativeAdLoad(ads: List<TTNativeAd>) {
                if (ads[0] == null) {
                    return
                }
                val bannerView = LayoutInflater.from(a).inflate(
                    R.layout.native_ad,
                    binding.bannerContainer,
                    false
                )
                if (bannerView == null) return

                binding.bannerContainer.removeAllViews()
                binding.bannerContainer.addView(bannerView)
                //绑定原生广告的数据
                setAdData(bannerView, ads[0])
            }
        })
    }

    fun setVideo() {
        Log.e("zalyyh", TTAdSdk.getAdManager().sdkVersion)
        val adSlot = AdSlot.Builder()
            .setCodeId("939505442")
            .setSupportDeepLink(true)
            .setImageAcceptedSize(1080, 1920)
            .setRewardName("金币") //奖励的名称
            .setRewardAmount(1)   //奖励的数量
            //必传参数，表来标识应用侧唯一用户；若非服务器回调模式或不需sdk透传
            //可设置为空字符串
            .setUserID("user123")
            .setOrientation(TTAdConstant.HORIZONTAL)  //设置期望视频播放的方向，为TTAdConstant.HORIZONTAL或TTAdConstant.VERTICAL
            .setMediaExtra("media_extra") //用户透传的信息，可不传
            .build()
        mTTAdNative!!.loadRewardVideoAd(adSlot, object : TTAdNative.RewardVideoAdListener {
            override fun onError(code: Int, message: String) {
                Toast.makeText(a, message, Toast.LENGTH_SHORT).show()
            }

            //视频广告加载后的视频文件资源缓存到本地的回调
            override fun onRewardVideoCached() {
                Toast.makeText(
                    a,
                    "rewardVideoAd video cached",
                    Toast.LENGTH_SHORT
                ).show()
            }

            //视频广告素材加载到，如title,视频url等，不包括视频文件
            override fun onRewardVideoAdLoad(ad: TTRewardVideoAd) {
                Toast.makeText(a, "rewardVideoAd loaded", Toast.LENGTH_SHORT)
                    .show()
                mttRewardVideoAd = ad
                //mttRewardVideoAd.setShowDownLoadBar(false);
                mttRewardVideoAd!!.setRewardAdInteractionListener(object :
                    TTRewardVideoAd.RewardAdInteractionListener {
                    override fun onSkippedVideo() {

                    }

                    override fun onVideoError() {

                    }

                    override fun onAdShow() {
                        Toast.makeText(
                            a,
                            "rewardVideoAd show",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    override fun onAdVideoBarClick() {
                        Toast.makeText(
                            a,
                            "rewardVideoAd bar click",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    override fun onAdClose() {
                        Toast.makeText(
                            a,
                            "rewardVideoAd close",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    override fun onVideoComplete() {
                        Toast.makeText(
                            a,
                            "rewardVideoAd complete",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    override fun onRewardVerify(
                        rewardVerify: Boolean,
                        rewardAmount: Int,
                        rewardName: String
                    ) {
                        Toast.makeText(
                            a,
                            "verify:" + rewardVerify + " amount:" + rewardAmount +
                                    " name:" + rewardName,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                })
                mttRewardVideoAd!!.setDownloadListener(object : TTAppDownloadListener {
                    override fun onIdle() {

                    }

                    override fun onDownloadActive(
                        totalBytes: Long,
                        currBytes: Long,
                        fileName: String,
                        appName: String
                    ) {

                    }

                    override fun onDownloadPaused(
                        totalBytes: Long,
                        currBytes: Long,
                        fileName: String,
                        appName: String
                    ) {

                    }

                    override fun onDownloadFailed(
                        totalBytes: Long,
                        currBytes: Long,
                        fileName: String,
                        appName: String
                    ) {

                    }

                    override fun onDownloadFinished(
                        totalBytes: Long,
                        fileName: String,
                        appName: String
                    ) {

                    }

                    override fun onInstalled(fileName: String, appName: String) {

                    }
                })
            }
        })
    }

    fun setVideo1() {
        //设置广告参数
        val adSlot = AdSlot.Builder()
            .setCodeId("939505086") //广告位id
            .setSupportDeepLink(true)
            .setAdCount(1) //请求广告数量为1到3条
//            .setImageAcceptedSize(900, 600) //根据广告平台选择的尺寸，传入同比例尺寸
            .build();
        //加载广告
        //step5:请求广告，对请求回调的广告作渲染处理
        mTTAdNative!!.loadInteractionExpressAd(adSlot, object : TTAdNative.NativeExpressAdListener {
            override fun onError(code: Int, message: String) {
                Toast.makeText(a, message, Toast.LENGTH_SHORT).show()
            }

            override fun onNativeExpressAdLoad(ads: List<TTNativeExpressAd>?) {
                if (ads == null || ads.size == 0) {
                    return
                }
                mTTAd = ads[0]
                bindAdListener(mTTAd!!)
//                startTime = System.currentTimeMillis()
                mTTAd!!.render()
            }
        })

    }

    private var mHasShowDownloadActive = false
    fun bindAdListener(ad: TTNativeExpressAd) {
        ad.setExpressInteractionListener(object : TTNativeExpressAd.AdInteractionListener {
            override fun onAdDismiss() {
                // "广告关闭")
            }

            override fun onAdClicked(view: View, type: Int) {
                // "广告被点击")
            }

            override fun onAdShow(view: View, type: Int) {
                // "广告展示")
            }

            override fun onRenderFail(view: View, msg: String, code: Int) {
                // Log.e("ExpressView", "render fail:" + (System.currentTimeMillis() - startTime))
                // "$msg code:$code")
            }

            override fun onRenderSuccess(view: View, width: Float, height: Float) {
                //  Log.e("ExpressView", "render suc:" + (System.currentTimeMillis() - startTime))
                //返回view的宽高 单位 dp
                // "渲染成功")
                mTTAd!!.showInteractionExpressAd(a)

            }
        })

        if (ad.interactionType != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return
        }
        ad.setDownloadListener(object : TTAppDownloadListener {
            override fun onIdle() {
                //  TToast.show(a, "点击开始下载", Toast.LENGTH_LONG)
            }

            override fun onDownloadActive(
                totalBytes: Long,
                currBytes: Long,
                fileName: String,
                appName: String
            ) {
                if (!mHasShowDownloadActive) {
                    mHasShowDownloadActive = true
                    // TToast.show(a, "下载中，点击暂停", Toast.LENGTH_LONG)
                }
            }

            override fun onDownloadPaused(
                totalBytes: Long,
                currBytes: Long,
                fileName: String,
                appName: String
            ) {
                //TToast.show(a, "下载暂停，点击继续", Toast.LENGTH_LONG)
            }

            override fun onDownloadFailed(
                totalBytes: Long,
                currBytes: Long,
                fileName: String,
                appName: String
            ) {
                //TToast.show(a, "下载失败，点击重新下载", Toast.LENGTH_LONG)
            }

            override fun onInstalled(fileName: String, appName: String) {
                // TToast.show(a, "安装完成，点击图片打开", Toast.LENGTH_LONG)
            }

            override fun onDownloadFinished(
                totalBytes: Long,
                fileName: String,
                appName: String
            ) {
                //  TToast.show(a, "点击安装", Toast.LENGTH_LONG)
            }
        })
    }


    private fun setAdData(nativeView: View, nativeAd: TTNativeAd) {
        (nativeView.findViewById(R.id.tv_native_ad_title) as TextView).text = nativeAd.title
        (nativeView.findViewById(R.id.tv_native_ad_desc) as TextView).text = nativeAd.description
        val imgDislike = nativeView.findViewById(R.id.img_native_dislike) as ImageView
        bindDislikeAction(nativeAd, imgDislike)
        if (nativeAd.imageList != null && !nativeAd.imageList.isEmpty()) {
            val image = nativeAd.imageList[0]
            if (image != null && image.isValid) {
                val im = nativeView.findViewById(R.id.iv_native_image) as ImageView
                Glide.with(this).load(image.imageUrl).into(im)
            }
        }
        val icon = nativeAd.icon
        if (icon != null && icon.isValid) {
            val im = nativeView.findViewById(R.id.iv_native_icon) as ImageView
            Glide.with(this).load(icon.imageUrl).into(im)
        }
        var mCreativeButton = nativeView.findViewById(R.id.btn_native_creative) as Button
        //可根据广告类型，为交互区域设置不同提示信息
        when (nativeAd.interactionType) {
            TTAdConstant.INTERACTION_TYPE_DOWNLOAD -> {
                //如果初始化ttAdManager.createAdNative(getApplicationContext())没有传入activity 则需要在此传activity，否则影响使用Dislike逻辑
                nativeAd.setActivityForDownloadApp(this)
                mCreativeButton.setVisibility(View.VISIBLE)
                // nativeAd.setDownloadListener(mDownloadListener) // 注册下载监听器
            }
            TTAdConstant.INTERACTION_TYPE_DIAL -> {
                mCreativeButton.setVisibility(View.VISIBLE)
                mCreativeButton.setText("立即拨打")
            }
            TTAdConstant.INTERACTION_TYPE_LANDING_PAGE, TTAdConstant.INTERACTION_TYPE_BROWSER -> {
                mCreativeButton.setVisibility(View.VISIBLE)
                mCreativeButton.setText("查看详情")
            }
            else -> {
                mCreativeButton.setVisibility(View.GONE)
                Toast.makeText(a, "交互类型异常", Toast.LENGTH_SHORT).show()
//                TToast.show(mContext, "交互类型异常")
            }
        }

        //可以被点击的view, 也可以把nativeView放进来意味整个广告区域可被点击
        val clickViewList = ArrayList<View>()
        clickViewList.add(nativeView)

        //触发创意广告的view（点击下载或拨打电话）
        val creativeViewList = ArrayList<View>()
        //如果需要点击图文区域也能进行下载或者拨打电话动作，请将图文区域的view传入
        //creativeViewList.add(nativeView);
        creativeViewList.add(mCreativeButton)

        //重要! 这个涉及到广告计费，必须正确调用。convertView必须使用ViewGroup。
        nativeAd.registerViewForInteraction(
            nativeView as ViewGroup,
            clickViewList,
            creativeViewList,
            imgDislike,
            object : TTNativeAd.AdInteractionListener {
                override fun onAdClicked(view: View, ad: TTNativeAd?) {
                    if (ad != null) {
                        Toast.makeText(a, "广告" + ad.title + "被点击", Toast.LENGTH_SHORT).show()

                    }
                }

                override fun onAdCreativeClick(view: View, ad: TTNativeAd?) {
                    if (ad != null) {
                        Toast.makeText(a, "广告" + ad.title + "被创意按钮被点击", Toast.LENGTH_SHORT).show()
//                        TToast.show(mContext, "广告" + ad.title + "被创意按钮被点击")
                    }
                }

                override fun onAdShow(ad: TTNativeAd?) {
                    if (ad != null) {
                        Toast.makeText(a, "广告" + ad.title + "展示", Toast.LENGTH_SHORT).show()
//                        TToast.show(mContext, "广告" + ad.title + "展示")
                    }
                }
            })

    }


    //接入网盟的dislike 逻辑，有助于提示广告精准投放度
    private fun bindDislikeAction(ad: TTNativeAd, dislikeView: View) {
        val ttAdDislike = ad.getDislikeDialog(this)
        ttAdDislike?.setDislikeInteractionCallback(object : TTAdDislike.DislikeInteractionCallback {
            override fun onSelected(position: Int, value: String) {
                binding.bannerContainer.removeAllViews()
            }

            override fun onCancel() {

            }
        })
        dislikeView.setOnClickListener {
            ttAdDislike?.showDislikeDialog()
        }
    }

}